package cn.jkgly.demo.web;

import cn.jkgly.demo.Helper.Https;
import cn.jkgly.demo.entity.Image;
import cn.jkgly.demo.entity.Phone;
import cn.jkgly.demo.service.GetHeathCard;
import cn.jkgly.demo.service.HealthCardService;
import cn.jkgly.demo.service.JsapiTicketUtil;
import cn.jkgly.demo.service.Sign;
import com.alibaba.fastjson.JSONObject;
import com.tencent.healthcard.model.HealthCardInfo;
import com.tencent.healthcard.model.ReportHISData;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;


@RestController
@RequestMapping("/api/jkgly")
public class HeathCardController {
    @Autowired
    GetHeathCard getHeathCard;
    @Autowired
    HealthCardService healthCardService;
    @ApiOperation(value = "保存用户基本信息")
    @PostMapping("/saveCardInfo")
    public JSONObject saveCardInfo(@RequestBody HealthCardInfo healthCardInfo){
        JSONObject jsonObject = new JSONObject();
        if(healthCardInfo.getIdNumber().length()!=18){
            jsonObject.put("retcode",-1);
            jsonObject.put("retmsg","身份证格式不正确");
            return jsonObject;
        }
        HealthCardInfo healthCardInfo1=healthCardService.findHealthCardTempByOpenId(healthCardInfo.getOpenId());
        if(healthCardInfo1==null){
            healthCardService.insertHealthCardTemp(healthCardInfo);
        }else{
            healthCardService.updateHealthCardTemp(healthCardInfo);
        }

        jsonObject.put("retcode",0);
        jsonObject.put("retmsg","成功");
       return jsonObject;
    }


    @ApiOperation(value = "获取手机号并注册电子健康卡")
    @PostMapping("/registerHealthCard")
    public JSONObject registerHealthCard(@RequestBody Phone phone){
        HealthCardInfo healthCardInfo=healthCardService.findHealthCardTempByOpenId(phone.getOpenId());
        healthCardInfo.setPhone1(phone.getPhone());
       return getHeathCard.getHeathCard(healthCardInfo);
    }


    @ApiOperation(value = "通过二维码获取电子健康卡")
    @PostMapping("/getHealthCardByCode")
    public JSONObject getHealthCardByCode(String qrCodeText ){
       return getHeathCard.getHealthCardByCode(qrCodeText);
    }


    @ApiOperation(value = "通过授权码获取电子健康卡")
    @PostMapping("/getHealthCardByHealthCode")
    public JSONObject getHealthCardByHealthCode(String healthCode ){
       return getHeathCard.getHealthCardByCode(healthCode);
    }


    @ApiOperation(value = "重定向")
    @GetMapping("/sendWechatCode")
    void sendWechatCode(HttpServletResponse response,HttpServletRequest request) throws IOException {
        //获取参数
        String openId = request.getParameter("openId");
        System.out.println("openID!!!!!!!!!!!!!"+openId);
        String url = request.getParameter("url");
        System.out.println("https://health.tengmed.com/open/getUserCode?redirect_uri=http%3a%2f%2fhealthcard.jkgly.cn/api/jkgly/getWechatCode?url="+url+"&openId="+openId);
        response.sendRedirect("https://health.tengmed.com/open/getUserCode?redirect_uri=http%3a%2f%2fhealthcard.jkgly.cn/api/jkgly/getWechatCode?url="+url+"?openId="+openId);
    }


    @ApiOperation(value = "获取wechatCode编码")
    @GetMapping ("/getWechatCode")
    void getWechatCode(HttpServletResponse response, HttpServletRequest request) throws IOException {

        String wechatCode = request.getParameter("wechatCode");
        String urls = request.getParameter("url");
        String url=urls.substring(0,urls.indexOf("?openId"));
        String openId=urls.substring(urls.indexOf("?openId=")+8);
        HealthCardInfo healthCardInfo=healthCardService.findHealthCardTempByOpenId(openId);
        if(healthCardInfo==null){
            healthCardService.insertHealthCardInfoWechatCode(wechatCode,openId);
        }else{
            healthCardService.updateHealthCardInfoWechatCode(wechatCode,openId);
        }
        response.sendRedirect("http://"+url+"?login=1");

    }


    @GetMapping("/sendRedirectHealthCard")
    void sendRedirectHealthCard(HttpServletResponse response,HttpServletRequest request) throws IOException {
        String openId = request.getParameter("openId");
        String url = request.getParameter("url");
        response.sendRedirect("https://health.tengmed.com/open/getHealthCardList?redirect_uri=http%3a%2f%2fhealthcard.jkgly.cn/api/jkgly/getHealthCode?url="+url+"?openId="+openId);
    }


    @ApiOperation(value = "获取healthCode编码")
    @GetMapping("/getHealthCode")
    void getHeathCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String urls = request.getParameter("url");
        String url=urls.substring(0,urls.indexOf("?openId"));
        String openId=urls.substring(urls.indexOf("?openId=")+8);
        String healthCode = request.getParameter("healthCode");
        JSONObject jsonObject =new JSONObject();
        if (healthCode== null){
            jsonObject.put("retcode",-1);
            jsonObject.put("retmsg","失败");
        }else{
            HealthCardInfo healthCardInfo=healthCardService.findHealthCardTempByOpenId(openId);
            if(healthCardInfo==null){
                healthCardService.insertHealthCardInfoHealthCode(healthCode,openId);
            }else{
                healthCardService.updateHealthCardInfoHealthCode(healthCode,openId);
            }
        }
        JSONObject healthInfo=getHeathCard.getHealthCardByHealthCode(healthCode);
        JSONObject commonOut=healthInfo.getJSONObject("commonOut");
        int  resultCode=commonOut.getIntValue("resultCode");
        if (resultCode!=0){
            response.sendRedirect("http://healthcard.jkgly.cn/regist.html");
        }else {
            JSONObject rsp =healthInfo.getJSONObject("rsp");
            JSONObject card =rsp.getJSONObject("card");
          Integer i= healthCardService.findHealthCardInfoByIdNumber(card.getString("idNumber"),openId);
           if(i==0){
               HealthCardInfo healthCardInfo =new HealthCardInfo();
               healthCardInfo.setPhone1(card.getString("phone1"));
               healthCardInfo.setName(card.getString("name"));
               healthCardInfo.setIdType(card.getString("idType"));
               healthCardInfo.setBirthday(card.getString("birthday"));
               healthCardInfo.setGender(card.getString("gender"));
               healthCardInfo.setHealthCardId(card.getString("healthCardId"));
               healthCardInfo.setOpenId(openId);
               healthCardInfo.setQrCodeText(card.getString("qrCodeText"));
               healthCardInfo.setAddress(card.getString("address"));
               healthCardInfo.setIdNumber(card.getString("idNumber"));
               healthCardInfo.setNation(card.getString("nation"));
               healthCardInfo.setPhone2(card.getString("phone2"));
               healthCardInfo.setPhid(card.getString("phid"));
               healthCardInfo.setPatid(card.getString("patid"));
               healthCardService.insertHealthCardInfo(healthCardInfo);
           }


            response.sendRedirect("http://"+url);
        }
    }
    @ApiOperation(value = "通过openId获取电子健康卡信息")
    @GetMapping("/getHealthCardByOpenId")
    public JSONObject getHealthCardByOpenId(String openId){
        List<HealthCardInfo> list =  healthCardService.findHealthCardInfoByOpenId(openId);
        ListIterator<HealthCardInfo> iterator=list.listIterator();
        while (iterator.hasNext()){
            HealthCardInfo healthCardInfo=iterator.next();
            String name =healthCardInfo.getName();
            String idNumber =healthCardInfo.getIdNumber();
            String phone1 =healthCardInfo.getPhone1();
            healthCardInfo.setName(name.replace(name.substring(1,2),"*"));
            healthCardInfo.setIdNumber(idNumber.replace(idNumber.substring(4,14),"**********"));
            healthCardInfo.setPhone1(phone1.replace(phone1.substring(2,9),"******"));
            iterator.remove();
            iterator.add(healthCardInfo);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retcode",0);
        jsonObject.put("retmsg","success");
        jsonObject.put("cardcount",list.size());
        jsonObject.put("cardlist",list);
        return jsonObject;
    }
   /* @ApiOperation(value = "获取code")
    @GetMapping("/getSendCode")
    public void getSendCode(HttpServletResponse response){
        try {
            response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3a06c113295b44c3&redirect_uri=http%3a%2f%2fhealthcard.jkgly.cn/api/jkgly/getCode&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    @ApiOperation(value = "获取code")
    @GetMapping("/getOpenId")
    public JSONObject getCode( String code) throws IOException {
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3a06c113295b44c3&secret=4d0807797b51489dc3be77bac85c9e79&code="+code+"&grant_type=authorization_code";
        String method= "GET";
        String result = Https.https(url,method);
        System.out.println(result);
        JSONObject jsonObject=JSONObject.parseObject(result);
        return jsonObject;

    }
   /* @ApiOperation(value = "将电子健康卡放入卡包接口")
    @GetMapping("/takeMsCard")
    public JSONObject takeMsCard(HttpServletResponse response,String qrCodeText) throws IOException {
      return getHeathCard.getOrderId(qrCodeText);
    }*/
    @ApiOperation(value = "将电子健康卡放入卡包接口")
    @GetMapping("/takeMsCard")
    public void takeMsCard(HttpServletResponse response,String qrCodeText) throws IOException {
      String orderId= getHeathCard.getOrderId(qrCodeText);
      response.sendRedirect("https://health.tengmed.com/open/takeMsCard?order_id="+orderId+"&redirect_uri=http%3a%2f%2fhealthcard.jkgly.cn");
    }
    @ApiOperation(value = "用卡数据检测")
    @GetMapping("/reportHISData")
    public JSONObject reportHISData(@RequestBody ReportHISData reportHISData) throws IOException {
       JSONObject jsonObject=getHeathCard.reportHISData(reportHISData);
       return jsonObject;
    }
    @ApiOperation(value = "通过OCR接口返回用户信息")
    @PostMapping("/registerByOcr")
    public JSONObject registerByOcr(@RequestBody Image image) throws IOException {
        JSONObject jsonObject=getHeathCard.registerByOcr(image.getImageContent());
        return jsonObject;
    }
    @ApiOperation(value ="获取签名等配置" )
    @GetMapping("/getWXConfigSignature")
    public Map getWXConfigSignature(String url){
        String jsapi_ticket = JsapiTicketUtil.getWXJsapiTicket();
        Map<String, String> ret = Sign.sign(jsapi_ticket, url);
        ret.put("appId","wx3a06c113295b44c3");
        return ret;
    }
}
